package com.example.canaldataes.consumer;

import com.alibaba.fastjson.JSONObject;
import com.example.canaldataes.es.entity.EsData;
import com.example.canaldataes.es.service.EsDataService;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class MQConsumer {

    @Autowired
    private EsDataService esDataService;

    @RabbitListener(queues = "${spring.rabbitmq.config.canal.queue-name}")
    @RabbitHandler
    public void consumer(Message message, Channel channel) throws IOException {
        String dataJson = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("消费数据：{}",dataJson);
        EsData esData = JSONObject.parseObject(dataJson, EsData.class);
        log.info("对象数据，{}",esData.toString());
        esDataService.saveData(esData);
        log.info("数据写入ES成功");
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
    }

}
